odoo.define('report_docx.ajax', function (require) {
    "use strict";

    var core = require('web.core');
    var ajax = require('web.ajax');
    var contentdisposition = require('web.contentdisposition');
    var download = require("web.download");
    var ws_download = require("report_docx.ws_download");

    function get_file(options) {
        var xhr = new XMLHttpRequest();

        var data;
        if (options.form) {
            xhr.open(options.form.method, options.form.action);
            data = new FormData(options.form);
        } else {
            xhr.open('POST', options.url);
            data = new FormData();
            _.each(options.data || {}, function (v, k) {
                data.append(k, v)
            });
        }
        data.append('token', 'dummy-because-api-expects-one');
        if (core.csrf_token) {
            data.append('csrf_token', core.csrf_token);
        }
        // IE11 wants this after xhr.open or it throws
        xhr.responseType = 'blob';

        // onreadystatechange[readyState = 4]
        // => onload (success) | onerror (error) | onabort
        // => onloadend
        xhr.onload = function () {
            var mimetype = xhr.response.type;
            if (xhr.status === 200 && mimetype !== 'text/html') {
                // replace because apparently we send some C-D headers with a trailing ";"
                // todo: maybe a lack of CD[attachment] should be interpreted as an error case?
                var header = (xhr.getResponseHeader('Content-Disposition') || '').replace(/;$/, '');
                var filename = header ? contentdisposition.parse(header).parameters.filename : null;

                if (this.responseURL.search('report/download')!==-1 && (filename.endsWith("xlsx") ||　filename.endsWith("docx"))){
                    ws_download(xhr.response, filename, mimetype)
                }else {
                    download(xhr.response, filename, mimetype);
                }
                // not sure download is going to be sync so this may be called
                // before the file is actually fetched (?)
                if (options.success) { options.success(); }
                return true;
            }

            if (!options.error) {
                return true;
            }
            var decoder = new FileReader();
            decoder.onload = function () {
                var contents = decoder.result;

                var err;
                var doc = new DOMParser().parseFromString(contents, 'text/html');
                var nodes = doc.body.children.length === 0 ? doc.body.childNodes : doc.body.children;
                try { // Case of a serialized Odoo Exception: It is Json Parsable
                    var node = nodes[1] || nodes[0];
                    err = JSON.parse(node.textContent);
                } catch (e) { // Arbitrary uncaught python side exception
                    err = {
                        message: nodes.length > 1 ? nodes[1].textContent : '',
                        data: {
                            name: String(xhr.status),
                            title: nodes.length > 0 ? nodes[0].textContent : '',
                        }
                    }
                }
                options.error(err);
            };
            decoder.readAsText(xhr.response);
        };
        xhr.onerror = function () {
            if (options.error) {
                options.error({
                    message: _("Something happened while trying to contact the server, check that the server is online and that you still have a working network connection."),
                    data: { title: _t("Could not connect to the server") }
                });
            }
        };
        if (options.complete) {
            xhr.onloadend = function () { options.complete(); }
        }

        xhr.send(data);
        return true;
    }

    ajax.get_file = get_file;

});